<template>
  <BasicDrawer v-bind="$attrs" @register="registerDrawer" :title="title" @ok="handleSubmit" width="700px">
    <BasicForm @register="registerForm" >
    </BasicForm>
  </BasicDrawer>
  <!--用户选择弹窗-->
  <SelectUserJoin @register="registerAddUserModal" @select="submitSelectedUser"/>
</template>
<script lang="ts" setup>
import { ref, computed, unref } from 'vue';
import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
import { useModal } from '/@/components/Modal';
import SelectUserJoin from '/@/views/system/tenantMember/SelectUserJoin.vue';
import { ColEx } from '/@/components/Form/src/types';
import { BasicForm, useForm } from '/@/components/Form/index';
import { formSchema } from './data';
import { saveOrUpdateLdp, getLdpTmpl, getPlatformConfig } from './api';
import { PlatformConfig } from './tenant.model';
import { useMessage } from '/@/hooks/web/useMessage';

// 自适应列配置
const wrapperCol: Partial<ColEx> = {
  xs: 24, // <576px
  sm: 24, // ≥576px
  md: 24, // ≥768px
  lg: 24, // ≥992px
  xl: 24, // ≥1200px
  xxl: 24, // ≥1600px
}

const { createMessage } = useMessage();
// 声明Emits
const emit = defineEmits(['success', 'register']);

const isUpdate = ref(true);
const selectdUser = ref<any>({})

const [registerAddUserModal, {openModal: openAddUserModal}] = useModal();

const [registerForm, { resetFields, setFieldsValue, validate, updateSchema }] = useForm({
  labelWidth: 80,
  schemas: formSchema,
  showActionButtonGroup: false,
  wrapperCol
});

const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
  await resetFields();
  setDrawerProps({ confirmLoading: false });
  isUpdate.value = !!data?.isUpdate;
  if (unref(isUpdate)) {
    try {
      setDrawerProps({ loading: true })
      data.record = await getLdpTmpl({ code: data.record.code });
      await setFieldsValue({
        ...data.record,
      });
    } finally {
      setDrawerProps({ loading: false })
    }
  }
});

const title = computed(() => (!unref(isUpdate) ? '新增身份源模板' : '编辑身份源模板'));
async function handleSubmit(v) {
  try {
    let values = await validate();
    setDrawerProps({ confirmLoading: true });
    await saveOrUpdateLdp({...values, userId: selectdUser.value.id}, isUpdate.value);
    closeDrawer();
    emit('success');
    createMessage.success(`${title.value}成功`)
  } finally {
    setDrawerProps({ confirmLoading: false });
  }
}

const handleSelectUser = () => {
  openAddUserModal(true, {
    isInviteTenantUser: false,
    singleSelect: true
  })
}

const submitSelectedUser = async (selectRows) => {
  if (selectRows && selectRows.length >= 1) {
    selectdUser.value = selectRows[0]
    console.log('selectRows', selectRows);
    setFieldsValue({userName: selectdUser.value.userName})
  }
}

</script>
